package com.nowcoder.community.util;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;

public class CookieUtil {

    //由于经常需要从HttpServletRequest对象中获取某个cookie中的值，所以封装为一个工具，方便复用
    public static String getValue(HttpServletRequest request, String key){
        //异常处理：排除空值参数
        if(request == null || key == null){
            //抛出异常
            throw new IllegalArgumentException("参数为空");
        }

        //从request中获取cookie数组
        Cookie[] cookies = request.getCookies();
        //如果不为空则遍历cookie数组寻找指定cookie,返回对应的值
        if(cookies != null){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals(key)){
                    return cookie.getValue();
                }
            }
        }
        //遍历结束都没有找到
        return null;

    }
}
